<?php
// +----------------------------------------------------------------------
// | 小牛Admin
// +----------------------------------------------------------------------
// | Website: www.xnadmin.cn
// +----------------------------------------------------------------------
// | Author: dav <85168163@qq.com>
// +----------------------------------------------------------------------

namespace app\common\controller;

use app\common\model\UserModel;
use app\common\service\TokenService;

class ApiBase extends Base
{
    #需token认证的操作
    protected $needAuth = [];

    #不需token认证的操作
    protected $noAuth = [];

    #用户token
    protected $token;

    #用户ID
    public $uid=0;

    /**
     * 初始化
     * @return void
     */
    public function initialize()
    {
        $this->token = $this->getToken();

        $action = $this->request->action();
        if( $this->token!='' || in_array($action,$this->needAuth) || (isset($this->needAuth[0])&&$this->needAuth[0]=='*') && !in_array($action,$this->noAuth) )
        {
            if( $payload = (new TokenService())->checkToken($this->token) ) {
                $this->uid = $payload['uid'];
            }
        }
    }

    /**
     * 获取token
     * @return array|string|null
     */
    protected function getToken()
    {
        //$authorization = $this->request->header('authorization');
        $token = $this->request->header('token');
        return $token;
    }

    /**
     * 当前用户
     */
    public function getUser()
    {
        if( $this->token!='' ) {
            if( $payload = (new TokenService())->checkToken($this->token) ) {
                $this->uid = $payload['uid'];
                if( $user = (new UserModel)->find($this->uid) ) {
                    return $user->hidden(['password','salt']);
                }
            }
        }
    }
}
